package com.skjanyou.applicationcase.filter;

import java.io.InputStream;

import com.skjanyou.annotation.api.enumclass.ResponseType;
import com.skjanyou.server.api.constant.StatusCode;
import com.skjanyou.server.api.inter.Filter;
import com.skjanyou.server.api.inter.Request;
import com.skjanyou.server.api.inter.Response;
import com.skjanyou.server.simplehttpserver.http.HttpHeaders;
import com.skjanyou.server.simplehttpserver.http.HttpProtocolLv1;
import com.skjanyou.server.simplehttpserver.http.HttpRequest;
import com.skjanyou.server.simplehttpserver.http.HttpResponse;
import com.skjanyou.server.simplehttpserver.http.HttpResponse.HttpResponseLine;
import com.skjanyou.util.ByteUtil;


// 静态资源过滤器
public class StaticResourcesFilter implements Filter {
	private String rootDir = "static";
	public StaticResourcesFilter(  ){
	}
	
	@Override
	public int priority() {
		return 0;
	}

	@Override
	public Filter init() {
		return this;
	}

	@Override
	public boolean doFilter(Request request, Response response) throws Exception {
		HttpRequest httpRequest = (HttpRequest) request;
		HttpResponse httpResponse = (HttpResponse) response;
		HttpResponseLine httpResponseLine = (HttpResponseLine) httpResponse.responseLine();
		String url = httpRequest.requestLine().url();
		HttpHeaders httpHeaders = httpResponse.getHttpHeaders();
		if( url.startsWith("/static") ){
			String resourcesPath = rootDir + url.substring(7);
			int versionIdx = resourcesPath.lastIndexOf("?");
			if( versionIdx != -1 ){
				resourcesPath = resourcesPath.substring(0, versionIdx );
			}
			String lowserName = resourcesPath.toLowerCase();
			if( lowserName.endsWith("js") ){
				httpHeaders.put("Content-Type", ResponseType.JS.getValue());
			}else if( lowserName.endsWith("html") ){
				httpHeaders.put("Content-Type", ResponseType.HTML.getValue());
			}else if( lowserName.endsWith("font") ){
				httpHeaders.put("Content-Type", ResponseType.HTML.getValue());
			}else if( lowserName.endsWith("css") ){
				httpHeaders.put("Content-Type", ResponseType.CSS.getValue());
			}else if( lowserName.endsWith("png") || lowserName.endsWith("jpg") || lowserName.endsWith("jpeg") ){
				httpHeaders.put("Content-Type", ResponseType.IMAGE.getValue());
			}
			System.out.println("加载包内资源:" + resourcesPath);
			ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
			InputStream is = classLoader.getResourceAsStream( resourcesPath );
			httpResponse.responseBody().setBodyContent(ByteUtil.convertToBytes(is, true));
			httpResponseLine.setProtocol(new HttpProtocolLv1());
			httpResponseLine.setStatusCode(StatusCode.Ok);
			return false;
		}
		return true;
	}

	@Override
	public Filter destroy() {
		return this;
	}

}
